import router from '@/router'
import { store } from '@/store'
import axios, { AxiosPromise, AxiosResponse } from 'axios'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { log } from 'mathjs'
// import { ElLoading } from 'element-plus'
type Code = 200 | 201 | 202 | 401 | 10000 | 0

interface ResponseData<T = any> {
  code: Code
  status: boolean
  data: T
  msg: string
  message: string
  success: boolean
}
// let loadingInstance:any = {}
// const cookie = 'eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsIm9yZ1R5cGUiOiJleHRlcm5hbCIsIm9yZ05hbWUiOiLkv6Hmga_ljJblip7lhazlrqQiLCJjcmVhdGVkIjoxNjkwNTA2OTUzMTY5LCJjTmFtZSI6IueuoeeQhuWRmCIsImV4cCI6MTcyMjA0Mjk1MywidXNlcmlkIjoiNCIsInRlbmFudCI6IjEiLCJvcmdJZCI6IjYwNDhlYzZlMWNmMDQ2YTI5OGY5OTYxOWZlMWUzNDA4In0.bh87ODsUC5f2yCpf9wE2oaPiSYMzDBRMU2tNUdDhXiMhswN5GHp1lz5MnlT2ndtWjnKMZ12jh2iunydOg0T7Og'
const cookie = () => localStorage.getItem('token')

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分
  // baseURL: process.env.VUE_APP_BASIC_API,
  // 超时
  timeout: 600000,
})
// request拦截器
service.interceptors.request.use(
  (config) => {
    // loadingInstance = ElLoading.service({ fullscreen: false })
    // console.log(cookie())
    // if (getToken()) {
    //   config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    //   config.headers['Lang'] = localStorage.getItem("lang");//添加国际化多语言header
    // }
    if (cookie()) {
      // console.log('Bearer ' + cookie())
      config.headers['Authorization'] = 'Bearer ' + cookie()
      config.headers['Lang'] = localStorage.getItem('lang') //添加国际化多语言header
    }
    return config
  },
  (error) => {
    // loadingInstance.close()
    console.log(error)
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  (response: AxiosResponse<ResponseData<any>>): AxiosPromise<ResponseData<any>> => {
    // loadingInstance.close()
    const code = response.data.code
    if (response.data.success) {
      return Promise.resolve(response)
    }
    if (code == 0) {
      return Promise.resolve(response)
    }
    // if(!response.data.code){
    //   return Promise.resolve(response);
    // }
    if (typeof response.data === 'string') {
      console.log(response.data, 'response.data')
      return Promise.resolve(response)
    }
    if (code === 401) {
      // const instance = new Dialog()
      // console.log(instance, 'instance')
      // instance?.init()
      ElMessageBox.alert('登录状态已过期，请重新登录', '系统提示', {
        confirmButtonText: '确认',
        type: 'warning',
        callback: () => {
          localStorage.removeItem('token')
          localStorage.removeItem('userInfo')
          localStorage.removeItem('permissions')
          localStorage.removeItem('routes')
          localStorage.removeItem('zhongziConfig')

          // router.push('/login')
          // location.reload()
          window.location.href = 'https://zhzz.checc.com.cn/login.html'
        },
      })
      // ElMessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
      //   confirmButtonText: '重新登录',
      //   cancelButtonText: '取消',
      //   type: 'warning',
      // }).then(() => {
      //   localStorage.removeItem('token')
      // localStorage.removeItem('userInfo')
      //   localStorage.removeItem('permissions')
      //   localStorage.removeItem('routes')
      //   location.reload()
      // })
    } else if (code !== 200) {
      // 10000的时候/流程的中心需要给予提示
      if (code == 10000) {
        return Promise.resolve(response)
      } else {
        console.log('后台业务出错',response.data);

        if (response.data.msg || response.data.message) {
          // ElNotification({
          //   type: 'error',
          //   title: response.data.msg || response.data.message,
          //   message: '',
          //   duration: 1000,
          // })
          ElMessage({
            // message: response.data.msg || response.data.message,
            message: response.data.msg || response.data.message ||  response.data.msg ,
            type: 'warning',
          })
        }
        if (response.data instanceof Blob) {
          return Promise.resolve(response)
          // return Promise.reject(response)
        } else {
          // ElMessage.error(response.data.msg)
          return Promise.reject(response)
        }
      }
    }

    console.log('response.data.msg', response)

    return Promise.resolve(response)
  },
  (error) => {
    // loadingInstance.close()
    let code = 0
    try {
      code = error.response.status
    } catch (e) {
      if (error.toString().indexOf('Error: timeout') !== -1) {
        ElNotification({
          type: 'error',
          title: '网络请求超时',
          message: '',
          duration: 22000,
        })
        return Promise.reject(error)
      }
      if (error.toString().indexOf('Error: Network Error') !== -1) {
        ElNotification({
          type: 'error',
          title: '网络请求错误',
          message: '',
          duration: 22000,
        })
        return Promise.reject(error)
      }
    }
    if (code === 504) {
      ElNotification({
        type: 'error',
        title: '请求超时',
        message: '',
        duration: 12000,
      })
      return Promise.reject(error)
    }
    if (code === 401) {
      ElMessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        store.dispatch('LogOut').then(() => {
          location.reload() // 为了重新实例化vue-router对象 避免bug
        })
      })
    } else if (code === 403) {
      history.pushState(null, 'base-data', '/401')
    } else {
      const errorMsg = error.response.data.message
      // if (errorMsg !== undefined) {
      //   ElNotification({
      //     type: 'error',
      //     title: errorMsg,
      //     message: '',
      //     duration: 1000,
      //   })
      // }
      console.log('ElMessage.error')

      if (error.response.data.msg) {
        ElMessage.error(error.response.data.msg)
      }
    }
    return Promise.reject(error)
  }
)

export default service
